package bbs;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import util.UnauthorizedAccessException;
import core.UserService;

@MultipartConfig
@WebServlet("/bbs/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            String s = new String(request.getParameter("bid").getBytes("8859_1"), "utf-8");
            int boardId = Integer.parseInt(s);
            s = new String(request.getParameter("aid").getBytes("8859_1"), "utf-8");
            int articleId = Integer.parseInt(s);
            Article article = ArticleDAO.selectById(articleId);
            BoardService boardService = new BoardService(request, boardId);
            if (boardService.canEditArticle(article))
                new UnauthorizedAccessException("게시글 편집 권한 없음");

            String returnUrl = new String(request.getParameter("returnUrl").getBytes("8859_1"), "utf-8");
            Part filePart = request.getPart("file");
            String fileName = getFileName(filePart);
            int fileSize = (int)filePart.getSize();
            if (fileSize > 0) {
                int userId = UserService.getCurrentUser(request.getSession()).getId();
                FileDAO.insert(articleId, userId, fileName, fileSize, filePart.getInputStream());
            }
            response.sendRedirect(returnUrl);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    private String getFileName(Part filePart) {
        for (String content : filePart.getHeader("content-disposition").split(";"))
            if (content.trim().startsWith("filename")) {
                String path = content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
                return new File(path).getName();
            }
        return null;
    }

    public static String makeUrl(HttpServletRequest request, int boardId, int articleId) {
        return String.format("%s/bbs/FileUploadServlet?bid=%s&aid=%s",
                request.getContextPath(), boardId, articleId);
    }

}
